import subprocess
import time
def main(cmd, timeout):
    p = subprocess.Popen(cmd, shell=True,
		    stdout=subprocess.PIPE,
		    stderr=subprocess.PIPE)
    fin_time = time.time() + timeout
    while p.poll() == None and fin_time > time.time():
        time.sleep(1)
    if fin_time <= time.time():
        p.kill()
        print 'killded'
        raise OSError('Process timeout reached')
    ret = p.returncode
    print 'communicate begin'
    out,err = p.communicate()
    return out,err,ret


if __name__ == '__main__':
    result = main(' /etc/init.d/samba restart', timeout=10)
    print result
